package com.lqs.sofp.dao.impl;

import com.lqs.sofp.dao.NewUsersDao;
import com.lqs.sofp.entity.User;
import com.lqs.sofp.utils.DbUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.List;

public class NewUserDaoLmpl implements NewUsersDao {
	private QueryRunner queryRunner = new QueryRunner();//与Statement类似，但是可自动释放连接放回连接池

	@Override
	public List<User> selectAll() {
		try {
			//格式query(String sql, ResultSetHandler rsh, Object... params)
			//返回一种对象结果
			List<User> userList = queryRunner.query(DbUtils.getConnection(), "select * from UserInfo;", new BeanListHandler<User>(User.class));
			return userList;
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return  null;
	}


	@Override
	public boolean delete(String userName) {
		
		 try {
			int result = queryRunner.update(DbUtils.getConnection(),"delete from UserInfo where UserName = ?;",userName);
			 if(result!=0) {
				 System.out.println("删除成功");
				 return true;
			 }else {
				 System.out.println("删除失败");
				 return false;
			 }
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return false;
	}

	@Override
	public boolean updata(User user) {
		try {
			 int result = queryRunner.update(DbUtils.getConnection(),"INSERT INTO UserInfo(Username,Password,Phone,Gender) VALUES(?,?,?,?);",user.getUsername(),user.getPassword(),user.getPassword(),user.getGender());
			 if(result!=0) {
				 System.out.println("添加成功");
				 return true;
			 }else {
				 System.out.println("添加失败");
				 return false;
			 }
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return false;
	}

	@Override
	public User select(String userName) {
		try {
			User user=queryRunner.query(DbUtils.getConnection(),"delete from UserInfo where Username=?",new BeanHandler<User>(User.class),userName);
			return user;
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;
	}
}